using BW.MesProject.BasicData.Application;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Host;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.Infrastructure;
using SqlSugar;
using Yitter.IdGenerator;
using ServiceManagement.Consul;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Linq;
using OfficeOpenXml;

/// <summary>
/// 基础数据微服务主程序
/// 配置依赖注入、数据库连接和中间件
/// </summary>

// 设置EPPlus许可证
ExcelPackage.License.SetNonCommercialOrganization("BW.MesProject");

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers().AddJsonOptions(a => a.JsonSerializerOptions.PropertyNamingPolicy = null);
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// 配置Swagger文档
builder.Services.AddSwaggerGen(a =>
{
    var file = Path.Combine(AppContext.BaseDirectory + "BW.MesProject.BasicData.Host.xml");
    a.IncludeXmlComments(file, true);
    var fileapplication = Path.Combine(AppContext.BaseDirectory + "BW.MesProject.BasicData.Application.xml");
    a.IncludeXmlComments(fileapplication, true);
});

// 注册HttpContext访问器
builder.Services.AddHttpContextAccessor();
// 注册SqlSugar ORM
builder.Services.AddSingleton<ISqlSugarClient>(s =>
{
    // 配置SqlSugar客户端
    SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
    {
        DbType = DbType.Oracle,
        ConnectionString = builder.Configuration.GetConnectionString("Str"),
        IsAutoCloseConnection = true,
    },
   db =>
   {
       // 每次请求的都会执行

       // 获取IOC对象需要传入上下文
       // var log=s.GetService<Log>()

       // 获取IOC对象需要传入上下文
       // var appServive = s.GetService<IHttpContextAccessor>();
       // var log= appServive?.HttpContext?.RequestServices.GetService<Log>();

       db.Aop.OnLogExecuting = (sql, pars) =>
       {

       };
   });
    #region 建表操作
    // 自动扫描并初始化所有实体表，排除Dto文件夹中的类
    var assembly = typeof(BW.MesProject.BasicData.Domain.BaseEntity).Assembly;
    var entityTypes = assembly.GetTypes()
        .Where(t => !t.IsInterface && !t.IsAbstract && t.IsClass 
               && t.Namespace != null 
               && t.Namespace.StartsWith("BW.MesProject.BasicData.Domain")
               && !t.Namespace.Contains(".Dto") // 排除Dto命名空间下的类
               && t.IsSubclassOf(typeof(BW.MesProject.BasicData.Domain.BaseEntity)))
        .ToList();
    
    Console.WriteLine($"找到 {entityTypes.Count} 个实体类，准备初始化表...");
    // 输出实体类名称，便于调试
    foreach (var type in entityTypes)
    {
        Console.WriteLine($"- {type.FullName}");
    }
    sqlSugar.CodeFirst.InitTables(entityTypes.ToArray());
    Console.WriteLine("所有实体表初始化完成");
    #endregion
    return sqlSugar;
});
builder.Configuration.Register();

// 使用Autofac作为依赖注入容器
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// 配置Autofac
builder.Host.ConfigureContainer<ContainerBuilder>(builder.ConfigureAutofac());

// 注册AutoMapper
builder.Services.AddAutoMapper(typeof(AutoMap));
// 配置雪花ID生成器
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
